<template>
  <el-container>
    <el-header height="40px">
      <el-col :span="14">
        <el-col :span="5">
          门诊挂号
        </el-col>
        <el-col :span="7" v-show="invoiceShow">
          <el-input v-model="invoiceNo" disabled placeholder="发票号"/>
        </el-col>
        <el-col :span="5" v-show="invoiceShow">
          <el-button @click="getInvoiceNo">更新发票号</el-button>
        </el-col>
      </el-col>
      <el-col :span="10">
        <div class="top-right-btn">
          <el-tooltip class="item" effect="dark" content="挂号信息列表" placement="top">
            <el-button type="text" round icon="el-icon-edit" @click="modularShow='registerList'">挂号信息列表</el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="挂号" placement="top">
            <el-button type="text" round icon="el-icon-edit" @click="handleAdd">挂号</el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="读卡" placement="top">
            <el-button type="text" round icon="el-icon-edit" @click="openCardReading">读卡</el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="重打" placement="top">
            <el-button type="text" round icon="el-icon-edit" @click="initForm">重打</el-button>
          </el-tooltip>
        </div>
      </el-col>
    </el-header>
    <el-main style="padding: 10px">
      <el-row v-show="componentShow('registerList')">
          <el-row style="padding: 2px">
            <el-form :model="queryParams" class="query" ref="queryParams" :inline="true" v-show="showSearch" label-width="100px">
              <el-col :span="4">
                <el-form-item prop="deptId">
                  <tree-select
                    v-model="queryParams.deptId"
                    :options="deptOptions"
                    :disable-branch-nodes="true"
                    :show-count="true"
                    placeholder="就诊科室"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item prop="status">
                  <el-select v-model="queryParams.status" clearable placeholder="就诊状态">
                    <el-option
                      v-for="data in statusOptions"
                      :key="data.dictValue"
                      :label="data.dictLabel"
                      :value="data.dictValue">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item prop="name">
                  <el-input
                    v-model="queryParams.pmsPatient.name"
                    placeholder="病历号/姓名"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
              </el-col>
              <el-form-item>
                <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </el-row>
        <div>
          <div class="top-right-btn" style="padding-bottom: 5px">
            <el-tooltip class="item" effect="dark" content="刷新" placement="top">
              <el-button size="mini" circle icon="el-icon-refresh" @click="handleQuery"/>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" :content="showSearch ? '隐藏搜索' : '显示搜索'" placement="top">
              <el-button size="mini" circle icon="el-icon-search" @click="showSearch=!showSearch"/>
            </el-tooltip>
          </div>
        </div>
          <div style="height:457px">
            <el-table border v-loading="loading" max-height="457px" :fit="true" :data="registrationList" style="width: 100%"
                      :row-style="{height: '30px'}" :cell-style="{padding: '3px'}">
              <el-table-column label="id" align="center" v-if="show" prop="id"/>
              <el-table-column label="患者id" align="center" v-if="show" prop="pmsPatient.id"/>
              <el-table-column label="科室id" align="center" v-if="show" prop="deptId"/>
              <el-table-column label="排班id" align="center" v-if="show" prop="skdId"/>
              <el-table-column label="操作" fixed="right" align="center" width="150px" >
                <template slot-scope="scope">
                  <el-button
                    size="small"
                    plain
                    type="primary"
                    @click="openReturnReading(scope.row)"
                    v-hasPermi="['dms:registration:edit']"
                    v-if="scope.row.status===1"
                  >退号
                  </el-button>
                  <el-button
                    size="small"
                    plain
                    type="success"
                    @click="openReturnReading"
                    v-hasPermi="['dms:registration:remove']"
                    v-if="scope.row.status===1"
                  >补打
                  </el-button>
                  <el-button
                    size="small"
                    plain
                    type="primary"
                    @click="queryPayList(scope.row)"
                    v-hasPermi="['dms:registration:edit']"
                    v-if="scope.row.status===2"
                  >缴费
                  </el-button>
                  <el-button
                    size="small"
                    plain
                    type="success"
                    @click="queryRefundList(scope.row)"
                    v-hasPermi="['dms:registration:remove']"
                    v-if="scope.row.status===2"
                  >退费
                  </el-button>
                  <el-button
                    size="small"
                    plain
                    type="info"
                    v-hasPermi="['dms:registration:remove']"
                    v-if="scope.row.status===4"
                  >无
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column label="状态" align="center" prop="status" >
                <template slot-scope="scope">
                  <el-tag :type='getStatusValue(scope.row.status,"listClass")'>
                    {{
                        getStatusValue(scope.row.status,'dictLabel')
                    }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="病历号" align="center" prop="pmsPatient.medicalRecordNo" width="220px"/>
              <el-table-column label="姓名" align="center" prop="pmsPatient.name" />
              <el-table-column label="性别" align="center" prop="pmsPatient.gender"  :formatter="genderFormat"/>
              <el-table-column label="出生日期" align="center" prop="pmsPatient.dateOfBirth" >
                <template slot-scope="scope">
                  <span>{{parseTime(scope.row.pmsPatient.dateOfBirth, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="就诊日期" align="center" prop="attendanceDate" >
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.attendanceDate, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="看诊科室" align="center" prop="sysDept.deptName" />
              <el-table-column label="就诊年龄" align="center" prop="patientAgeStr"/>
            </el-table>
          </div>
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        <!-- 退号弹出框 -->
        <el-dialog :title="returnTitle" :visible.sync="returnOpen"  width="500px" append-to-body>
          <el-form ref="returnForm" :model="returnForm"  :rules="returnRules" label-width="100px">
            <el-form-item label="发票Id" v-show="false">
              <el-input v-model="returnForm.id"></el-input>
            </el-form-item>
            <el-form-item label="挂号Id" v-show="false">
              <el-input v-model="returnForm.registrationId"></el-input>
            </el-form-item>
            <el-form-item label="排班id" v-show="false">
              <el-input v-model="returnForm.skdId"></el-input>
            </el-form-item>
            <el-form-item label="发票号">
              <el-input v-model="returnForm.invoiceNo" :disabled="true" placeholder="发票号"></el-input>
            </el-form-item>
            <el-form-item label="冲红发票号" prop="redInvoiceNo">
              <el-input v-model="returnForm.redInvoiceNo" placeholder="冲红发票号"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitReturnForm">确 定</el-button>
            <el-button @click="returnCancel">取 消</el-button>
          </div>
        </el-dialog>
      </el-row>
      <!--挂号添加页面-->
      <add-registration ref="addRegistration" @addSuccessBack="addSuccessBack" @notify="notify" :invoiceNo="invoiceNo"
                        :patientObject="patientObject" v-show="componentShow('addRegister')">
      </add-registration>
      <!--缴费页面-->
      <pay-list ref="pay" v-show="componentShow('payList')" @notify="notify" :invoiceNo="invoiceNo"
                @handleBack="handleBack">
      </pay-list>
      <refund-list ref="refund" v-show="componentShow('refundList')" @notify="notify" :newInvoiceNo="invoiceNo"
                   @handleBack="handleBack">
      </refund-list>
      <!-- 读卡对话框 -->
      <el-dialog :title="cardTitle" :visible.sync="open" width="500px" append-to-body>
        <el-tag type="info">身份证号</el-tag>
        <el-form ref="cardForm" :model="cardForm" :rules="cardRules" label-width="80px">
          <el-form-item prop="identificationNo" label-width="0">
            <el-input v-model="cardForm.identificationNo" placeholder="请输入身份证号"/>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitCardForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<script>
  import {RegistrationPatientList, handleBounce} from "@/api/dms/registration";
  import ScrollPane from "../../../layout/components/TagsView/ScrollPane";
  import Icons from "../../components/icons/index";
  import addRegistration from "./addRegistration";
  import payList from "./payList";
  import refundList from "./refundList";
  // 患者
  import {getPatientByIdentificationNo} from "@/api/pms/patient";
  // 发票
  import {queryInvoiceNo, queryByRegistrationId} from "@/api/bms/invoice_record";
  // 若依css
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  // 树下拉框
  import TreeSelect from "@riophae/vue-treeselect";
  // 科室
  import {treeselect} from "@/api/system/dept";
  // 字典表
  import {listData} from "@/api/system/dict/data";

  export default {
    name: "Registration",
    components: {Icons, ScrollPane, addRegistration, payList, refundList, TreeSelect},
    data() {
      return {
        // 遮罩层
        loading: true,
        notifyPromise: Promise.resolve(),
        //隐藏
        show: false,
        // 模块隐藏
        modularShow: 'registerList',
        // 发票隐藏
        invoiceShow: false,
        // 状态的对应的值
        statusOptions: [],
        // 状态的对应的颜色
        statusOptionsColour: {"1": "warning", "2": "danger", "3": "success", "4": "info"},
        // 选中数组
        ids: [],
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 就诊(门诊)信息(一个病人一个病历号，多次就诊，多次就诊信息)表格数据
        registrationList: [],
        // 弹出层标题
        cardTitle: "",
        // 退号弹出层标题
        returnTitle: "",
        // 是否显示弹出层
        open: false,
        // 退号弹出层
        returnOpen: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          pmsPatient: {
            name: null,
            medicalRecordNo: null
          },
          deptId: undefined,
          status: undefined
        },
        // 读卡表单
        cardForm: {},
        // 退号表单
        returnForm: {},
        //发票号
        invoiceNo: null,
        // 读卡表单校验
        cardRules: {
          identificationNo: [
            {
              required: true, message: "身份证不能为空", trigger: 'blur'
            }, {
              pattern: /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/,
              message: '请输入合法身份证号'
            }
          ]
        },
        //退号表单校验
        returnRules: {
          redInvoiceNo: [
            {
              required: true, message: "冲红发票号不能为空", trigger: 'blur'
            }
          ]
        },
        // 患者对象
        patientObject: {},
        // 给子组件缴费页面
        payParams: null,
        // 科室列表
        deptOptions: [],
      };
    },
    created() {
      this.getDeptList();
      this.getRegistrationStatusList({dictType: "dms_registration_status"});
    },
    watch: {
      // 监听姓名查询参数的变化
      'queryParams.pmsPatient.name'(val) {
        // 将值赋给 病历号
        this.queryParams.pmsPatient.medicalRecordNo = val;
      },
      // 监听组件的显示
      'modularShow'(val) {
        this.invoiceShow = val === "addRegister" || val === "payList" || val === "refundList";
      }
    },
    methods: {
      /** 查询就诊(门诊)信息(一个病人一个病历号，多次就诊，多次就诊信息)列表 */
      getList() {
        this.loading = true;
        RegistrationPatientList(this.queryParams).then(response => {
          this.registrationList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
      },
      // 退号取消按钮
      returnCancel() {
        this.returnOpen = false;
      },
      // 读卡表单重置
      cardReset() {
        this.cardForm = {
          identificationNo: null
        };
        this.resetForm("cardForm");
      },
      // 退号表单重置
      returnReset() {
        this.returnForm = {
          registrationId: null,
          redInvoiceNo: null,
          invoiceNo: null,
          skdId: null,
          id: null
        };
        this.resetForm("returnForm");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.queryParams = {
          pageNum: 1,
          pageSize: 10,
          pmsPatient: {
            name: null,
            medicalRecordNo: null
          },
          deptId: undefined,
          status: undefined
        };
        this.resetForm("queryParams");
        this.handleQuery();
      },
      /** 挂号按钮操作 */
      handleAdd() {
        this.modularShow = 'addRegister';
      },
      /** 打开读卡 */
      openCardReading() {
        this.cardReset();
        this.open = true;
        this.cardTitle = "读卡(获取用户身份证号)";
      },
      /** 打开退号 */
      openReturnReading(data) {
        this.returnReset();
        this.returnOpen = true;
        this.returnTitle = "退号";
        this.returnForm.skdId = data.skdId;
        this.returnForm.registrationId = data.id;
        this.queryByRegistrationId(data.id);
      },
      /** 读卡提交按钮 */
      submitCardForm() {
        // 表单验证
        this.$refs["cardForm"].validate(valid => {
          if (valid) {
            getPatientByIdentificationNo(this.cardForm.identificationNo).then(response => {
              if (response.data) {
                this.patientObject = response.data;
                this.msgSuccess("读卡成功");
                this.open = false;   //关闭读卡弹出框
                this.modularShow = 'addRegister'; //打开添加读卡页面
                this.getInvoiceNo();            //更新发票号
              } else {
                this.msgError("没有该身份证号");
              }
            });
          }
        })
      },
      /** 退号提交按钮 */
      submitReturnForm() {
        // 表单验证
        this.$refs["returnForm"].validate(valid => {
          if (valid) {
            handleBounce(this.returnForm).then(response => {
              if (response.code === 200) {
                this.msgSuccess("退号成功");
                // 弹窗关闭
                this.returnCancel();
                // 刷新列表
                this.getList();
              }
            });
          }
        })
      },
      /**性别格式转换*/
      genderFormat(row, column, cellValue) {
        if (cellValue === 0) {
          return "男"
        } else if (cellValue === 1) {
          return "女"
        }
      },
      /** 获取发票号*/
      getInvoiceNo() {
        queryInvoiceNo().then(response => {
          this.invoiceNo = response.data;
        });
      },
      /** 挂号成功回调*/
      addSuccessBack() {
        this.open = false;
        this.getList();
        this.invoiceNo = null;
        this.modularShow = 'registerList';
      },
      /** 重打按钮*/
      initForm() {
        // 调用子组件的方法
        this.$refs.addRegistration.reset();
        this.invoiceNo = null;
      },
      /** 根据挂号Id 获取发票Id*/
      queryByRegistrationId(registrationId) {
        queryByRegistrationId(registrationId).then(response => {
          this.returnForm.redInvoiceNo = response.data.invoiceNo;
          this.returnForm.invoiceNo = response.data.invoiceNo;
          this.returnForm.id = response.data.id;
        })
      },
      /**
       * 组件显示隐藏控制
       */
      componentShow(showName) {
        return this.modularShow === showName;
      },
      // 查询缴费列表
      queryPayList(data) {
        this.$refs.pay.getPayList(data);
        this.modularShow = 'payList';
      },
      // 查询退费列表
      queryRefundList(data) {
        this.$refs.refund.getRefundList(data);
        this.modularShow = 'refundList';
      },
      /** 缴费退费回调 */
      handleBack(flag, viewName) {
        if (flag) {
          this.getInvoiceNo();
          this.invoiceNo = null;
        } else {
          this.modularShow = viewName;
        }
      },
      // 消息提示
      notify(msg) {
        this.notifyPromise = this.notifyPromise.then(this.$nextTick).then(() => {
          this.$notify({
            title: "警告",
            message: msg,
            dangerouslyUseHTMLString: true,
            type: 'warning',
          });
        })
      },
      /** 科室列表获取 */
      getDeptList() {
        treeselect().then(response => {
          this.deptOptions = response.data;
        });
      },
      /** 就诊信息状态列表获取 */
      getRegistrationStatusList(params) {
        listData(params).then(response => {
          this.statusOptions = response.rows;
          this.getList();
        });
      },
      /** 从就诊信息状态列表取值 */
      getStatusValue(key,property){
        if(this.statusOptions.length>0){
          let  option = this.statusOptions.find((option) => (option.dictValue ===key.toString()));
          if(option!==undefined){
            return option[property];
          }
        }
      }
    }
  };
</script>

<style scoped>
  .el-header {
    background-color: #f2f2f3;
    color: #333;
    text-align: center;
    line-height: 40px;
  }

  .app-padding {
    padding: 10px;
  }

  .query .el-form-item{
    height: 10px;
  }
</style>
